﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Toolbox
{
    public partial class dlgTags : Form
    {
        private ToolboxDataContext dbToolbox = new ToolboxDataContext(Properties.Settings.Default.UserToolboxConnectionString);
        int nToolID = 0;
        List<ToolTag> lTags;

        public dlgTags(int nID)
        {
            InitializeComponent();
            nToolID = nID;
        }

        private void dlgTags_Load(object sender, EventArgs e)
        {
            var result = from T in dbToolbox.ToolTags where T.ToolID == nToolID select T;
            lTags = result.ToList();

            using (SqlConnection cn = new SqlConnection(dbToolbox.Connection.ConnectionString))
            {
                cn.Open();
                using (SqlCommand cm = new SqlCommand("select tag from tags order by tag", cn))
                {
                    using (SqlDataReader rdr = cm.ExecuteReader())
                    {
                        while (rdr.Read())
                        {
                            chklstTag.Items.Add(rdr[0].ToString(),IsItemChecked(rdr[0].ToString()));
                        }
                    }
                }
            }
        }

        private bool IsItemChecked(string tag)
        {
            try
            {
                foreach (var curTag in lTags)
                {
                    if (curTag.Tag1.Tag1 == tag)
                    {
                        return true;
                    }
                }
            }
            catch
            {
                // null tag is the same as no tag                
            }
            return false;
        }

        private void dlgTags_FormClosing(object sender, FormClosingEventArgs e)
        {
            dbToolbox.RemoveAllToolTags(nToolID);
            foreach (object itemChecked in chklstTag.CheckedItems)
            {
                dbToolbox.AddToolTag(nToolID, itemChecked.ToString());
            }
        }
    }
}
